<?php
declare(strict_types=1);
/**
 * Created by PhpStorm
 * User: Administrator
 * Date: 2023/8/4
 * Time: 14:59:07
 */

namespace Service\CommodityService;

use App\Model\BbcModel\GoodsSupplyClass;
use Service\Code\Normal;
use App\Model\BbcModel\Goods;
use App\Model\BbcModel\GoodsClass;
use Service\BaseService;
use Hyperf\DbConnection\Db;
use App\Model\BbcModel\GoodsBrand;
use Service\EsService\EsPublishMsgService;
use App\Model\BbcModel\MnStoreGoods;

/**
 * 映射关联分类
 */
class RelevanceClassService extends BaseService
{

    public function makeWhere($param){

        $where = [
            ['cid','=',$param['cid']],
            ['sid','=',$param['sid']],
        ];

        if(isset($param['supply_class_id']) && $param['supply_class_id'] != ''){
            $where[] = ['id','=',$param['supply_class_id']];
        }

        if (isset($param['class_id']) && $param['class_id'] != 0) {
            $children = GoodsClass::instance()->whereIn('pid', $param['class_id'])->where('df', 0)->where('show', 1)->pluck('id')->toArray();
            $children[] = $param['class_id'];
            $where[] = [function($query) use ($children){
                $query->whereIn('class_id',$children);
            }];
        }

        if(isset($param['status']) && $param['status'] != ''){
            if($param['status'] == 1){
                $where[] = ['class_id','<>',0];
            }else{
                $where[] = ['class_id','=',0];
            }
        }
        return $where;
    }

    /**
     * 关联分类列表
     * @param $param
     * @return array
     */
    public function relevanceClassList($param){
        $page = $param['page'] ?? 1;
        $limit = $param['limit'] ?? 10;

        $where = $this->makeWhere($param);
        $data_list = GoodsSupplyClass::instance()
            ->where($where)
            ->paginate($limit,['id','name','class_id','supply_id'],'page',$page);
        $total = $data_list->total();
        $list = $data_list->items();

        foreach ($list as &$v){
            $v['goods_num'] = Goods::instance()->where(['supply_class_id'=>$v['id'],'cid'=>$param['cid'],'df'=>0,'is_trade'=>0])->count();
            $v['status'] = $v['class_id'] == 0 ? '否' : '是';

            if($v['class_id']){
                $v['class_id_name'] = GoodsClass::instance()->where(['cid'=>$param['cid'],'id'=>$v['class_id']])->value('name');
            }else{
                $v['class_id_name'] = '';
            }
        }
        return Normal::returnCode(Normal::SUC,'请求成功',['list'=>$list,'total'=>$total]);
    }

    /**
     * 供应商分类列表
     * @param $param
     * @return array
     */
    public function supplyClassList($param){
        $goodsSupplyClass = GoodsSupplyClass::instance()
            ->where(['cid'=>$param['cid']])
            ->select('id','name')
            ->get()->toArray();

        return Normal::returnCode(Normal::SUC,'请求成功',$goodsSupplyClass);
    }

    /**
     * 渠道分类列表
     * @param $param
     * @return array
     */
    public function goodsClassList($param){
        $data_list = GoodsClass::instance()
            ->where(['df'=>0,'cid'=>$param['cid']])
            ->get()->toArray();
        return Normal::returnCode(Normal::SUC,'请求成功',$data_list);
    }

    public function relationClass($param){
        if(!isset($param['supply_class_ids']) || !$param['supply_class_ids']){
            return Normal::returnCode(Normal::FAIL,'缺少供应商分类');
        }

        if(!isset($param['class_id']) || !$param['class_id']){
            return Normal::returnCode(Normal::FAIL,'缺少渠道商品分类');
        }

        $supply_class = GoodsSupplyClass::instance()
            ->where(['cid'=>$param['cid']])
            ->whereIn('id',$param['supply_class_ids'])
            ->get()->toArray();
        if(!$supply_class){
            return Normal::returnCode(Normal::FAIL,'供应商分类不存在');
        }

        $new_supply_class = [];
        $new_goods_class = [];
        foreach($supply_class as $k=>$v){
            $new_supply_class[] = $v['id'];
            $new_goods_class[] = $v['id'];
        }
        Db::beginTransaction();
        try{
            GoodsSupplyClass::instance()
                ->whereIn('id',$new_supply_class)
                ->update(['class_id'=>$param['class_id']]);
            Goods::instance()
                ->where(['cid'=>$param['cid']])
                ->whereIn('supply_class_id',$new_goods_class)
                ->update(['class_id'=>$param['class_id']]);
            $this->updateIndex($param);
            Db::commit();
        }catch (\Exception $e){
            Db::rollBack();
            return Normal::returnCode(Normal::FAIL,'关联失败'.$e->getMessage());
        }

        return Normal::returnCode(Normal::SUC,'关联成功');
    }

    /**
     * 更新商品ES
     * @param $param
     * @return void
     */
    public function updateIndex($param){
        $cid = $param['cid'];
        $new_goods_classid = $param['class_id'];
        $brandList = Goodsbrand::instance()
            ->where(['cid'=>$cid,'df'=>0])
            ->select(['id','name'])
            ->get()->toArray();
        $brandList = array_column($brandList,'name','id');
        $goodsList = Goods::instance()
            ->where(['class_id'=>$new_goods_classid,'cid'=>$cid,'df'=>0])
            ->select(['id','name','brand_id','status','is_trade'])
            ->get()->toArray();
        if($goodsList){
            $ids = array_column($goodsList,'id');
            $goodsIndex = array_column($goodsList,null,'id');
            $channelInsert = [];
            //大贸批次商品不能进行代发售卖,更新渠道搜索索引
            foreach ($goodsList as $v){
                if($v['is_trade']==0){
                    $updateIndexData['id']                   = $v['id'];
                    $updateIndexData['goodsId']              = $v['id'];
                    $updateIndexData['name']                 = $v['name'];
                    $updateIndexData['classifyID']           = $new_goods_classid;
                    $updateIndexData['channelID']            = $cid;
                    $updateIndexData['brandName']            = $brandList[$v['brand_id']];
                    $updateIndexData['isTrade']              = 0;
                    $updateIndexData['isChannelGoodsActive'] = $v['status'] > 0;
                    $channelInsert[]                         = $updateIndexData;
                }
            }
            if(!empty($channelInsert)){
                EsPublishMsgService::instance()->channelESMessageProducer($channelInsert);
            }
            //更新店铺搜索索引
            $storeGoodsList = MnStoreGoods::instance()
                ->whereIn('goods_id',$ids)
                ->select(['id','mn_sid','status','goods_id'])
                ->get()->toArray();
            $insertData=[];
            foreach ($storeGoodsList as $keys=>$values){
                $insertItem['id']                   = $values['id'];
                $insertItem['goodsId']              = $values['goods_id'];
                $insertItem['name']                 = $goodsIndex[$values['goods_id']]['name'];
                $insertItem['classifyID']           = $new_goods_classid;
                $insertItem['storeID']              = $values['mn_sid'];
                $insertItem['channelID']            = $cid;
                $insertItem['isTrade']              = $goodsIndex[$values['goods_id']]['is_trade'];
                $insertItem['brandName']            = $brandList[$goodsIndex[$values['goods_id']]['brand_id']];
                $insertItem['isStoreGoodsActive']   = $values['status'] > 0;
                $insertItem['isChannelGoodsActive'] = $goodsIndex[$values['goods_id']]['status'] > 0;
                $insertData[]                       = $insertItem;
            }
            if(!empty($insertData)){
                EsPublishMsgService::instance()->storeESMessageProducer($insertData);
            }
        }
    }
}